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AMPNavfRxfRSDNgqHqlUD3GPV+NpjuxGR9oQPBvmrWU58A+CBbPTZqMvtpguUvzIBAkFMmf8OlW4qSAbbvJCtMQJBAKarMU+cWLX7XLPc0Bib7MiOMKU2DuhvA/xve8+mKbmKz+Tbci4UyS2HEfyYYecToe4PuFex3O/d3g+abYZffgY=";

/**
 * RSA加密方法
 * 请求时对参数进行加密
 */
function encryptionByRSA(data) {
    let encrypt = new JSEncrypt();
    encrypt.setPublicKey(PUBLIC_KEY);
    let encrypted = encrypt.encrypt(data);
    return encrypted;
}

/**
 * RSA解密方法
 * 响应返回时对结果进行解密
 */
function decryptByRSA(data) {
    let decrypt = new JSEncrypt();
    decrypt.setPrivateKey(PRIVATE_KEY);
    let decrypted = decrypt.decrypt(data);
    return decrypted;
}

//DES加密
function encryptByDES(message, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var encrypted = CryptoJS.AES.encrypt(message, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}

//DES解密
function decryptByDES(ciphertext, key) {

    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var decrypted = CryptoJS.AES.decrypt({
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
    }, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });

    return decrypted.toString(CryptoJS.enc.Utf8);
}

/**
 * 获取签名信息
 * @param {*} ticket 临时票据
 * @param {*} nonce 可以是任何字符串；
 * @param {*} timeStamp 时间戳
 * @param {*} url
 */
function getJsApiSignature(ticket, nonce, timeStamp, url) {
    let plainTex = "jsapi_ticket=" + ticket + "&noncestr=" + nonce + "&timestamp=" + timeStamp + "&url=" + url;
    let signature = CryptoJS.SHA1(plainTex).toString();
    return signature;
}
//随机字符串
function randomString(length) {
    var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var result = '';
    for (var i = length; i > 0; --i)
        result += str[Math.floor(Math.random() * str.length)];
    return result;
}

//全局 axios 默认值

const instance = axios.create({
    baseURL: 'http://localhost:8000',
    timeout: 3000
});

// 添加请求拦截器
instance.interceptors.request.use(config => {

    let access_token = localStorage.getItem("access_token");
    let refresh_token = localStorage.getItem("refresh_token");

    const key = randomString(16);
    config.headers['desKey'] = encryptionByRSA(key);

    if (access_token != null && access_token != ''){
        config.headers['Authorization'] = "Bearer "+access_token;
        config.headers['Content-type'] = 'application/json; charset=utf-8';
        if (config.data.noEncrypt){
            config.data = encryptByDES(JSON.stringify(config.data.data),key);
        }else {
            config.data = config.data.data;
        }
    }else {
        config.data=Qs.stringify(config.data.data);
        config.headers['Content-type'] = 'application/x-www-form-urlencoded;';
    }

    return config
}, error => {
    return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(response => {

    if (response != null && response != undefined && response != ''){

    }

    //加密解密开关
    if (response.data.noEncrypt){
       return  decryptByDES(response.data.data,decryptByRSA(response.data.desKey));
    }else {
        return response.data ;
    }
}, error => {
    return Promise.resolve(error.response)
})

/**
 * 请求封装
 */
function baseRequest(url, method, data, {noEncrypt = false}) {
    //合并加密开关
    let str=Object.assign({},{"data":data},{"noEncrypt":noEncrypt});

    return new Promise((resolve, reject) => {
        instance.request({
            url:url,
            method: method || 'GET',
            data: str,
        }).then(function (data) {
            resolve(data)
        }).then(function (error) {
            reject(error)
        })
    });

}

const request = {};

['get', 'post',  'delete','put', 'head', 'options', 'trace', 'connect'].forEach((method) => {
    request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});

export default request;